package com.md.application.goods;

import com.md.api.goods.GoodsTypeApi;
import com.md.application.assembler.GoodsTypeAssembler;
import com.md.domain.model.GoodsType;
import com.md.domain.service.GoodsTypeDomainService;
import com.md.model.request.goods.InsertGoodsTypeRequest;
import com.md.model.system.CommonResult;
import com.md.value.constants.CodeConstants;
import com.md.value.constants.GoodsTypeConstants;
import com.md.value.enums.ErrorEnum;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author 刘骄阳
 * 2022-03-12 15:20
 */
@Service
public class GoodsTypeApplicationService implements GoodsTypeApi {
  @Resource
  GoodsTypeDomainService goodsTypeDomainService;

  /**
   * 后台添加商品类别
   *
   * @param request 商品类别
   * @return 操作结果
   */
  @Override
  public CommonResult<Long> insert(InsertGoodsTypeRequest request) {
    CommonResult<ErrorEnum> judgeResult = GoodsTypeAssembler.judgeRequest(request);
    if (!Objects.equals(judgeResult.getCode(), CodeConstants.SUCCESS_CODE)) {
      return CommonResult.error(judgeResult.getData());
    }

    GoodsType parentGoodsType = null;
    // 去数据库查询最大的sort
    Long sort = goodsTypeDomainService.getRepository().selectChildrenCount(request.getParentId());
    if (request.getParentId() != GoodsTypeConstants.DEFAULT_ROOT_GOODS_TYPE_ID) {
      parentGoodsType = goodsTypeDomainService.getRepository().selectById(request.getParentId());
    }
    GoodsType goodsType = GoodsTypeAssembler.build(request, parentGoodsType, sort);
    goodsTypeDomainService.getRepository().insert(goodsType);
    if (ObjectUtils.isEmpty(goodsType.getRootId())) {
      // 根id为空说明是,顶级分类
      goodsType.setRootId(goodsType.getId());
      goodsTypeDomainService.getRepository().update(goodsType);
    }
    return CommonResult.success(goodsType.getId());
  }
}
